package org.aspose;

import com.aspose.pdf.*;
import com.aspose.pdf.facades.PdfContentEditor;
import com.aspose.pdf.facades.PdfConverter;
import com.aspose.pdf.facades.PdfFileEditor;
import com.aspose.pdf.facades.PdfFileSignature;
import com.aspose.words.FolderFontSource;
import com.aspose.words.FontSettings;
import com.aspose.words.FontSourceBase;
import com.aspose.words.SystemFontSource;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileWriter;

/**
 * @author lixing
 * @version V1.0
 * @ClassName:
 * @Description:
 * @Date 2024/8/19 16:30
 */
public class ManipulatePdf {
    public static void main(String[] args) {

        // mergePdf("C:\\Users\\XingL\\Desktop\\bb2.pdf", "C:\\Users\\XingL\\Desktop\\bb1.pdf", "C:\\Users\\XingL\\Desktop\\bb3.pdf");

        String context = "<!DOCTYPE html>\n" +
                "<html xmlns:th=\"http://www.thymeleaf.org\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title th:text=\"${report.title}\">Report Title</title>\n" +
                "    <style>\n" +
                "        body { font-family: Arial, sans-serif; }\n" +
                "        .cover { background-color: #f0f0f0; padding: 20px; text-align: center; }\n" +
                "        .header { background-color: #e0e0e0; padding: 20px; text-align: center; }\n" +
                "        .content { padding: 20px; }\n" +
                "        h1 { color: #333; }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div class=\"cover\">\n" +
                "    <h1 th:text=\"${report.title}\">Cover Page</h1>\n" +
                "</div>\n" +
                "<div class=\"header\">\n" +
                "    <p th:text=\"${report.header}\">Header Content</p>\n" +
                "</div>\n" +
                "<div class=\"content\">\n" +
                "    <table border=\"1\" style=\"width:100%;\">\n" +
                "        <thead>\n" +
                "        <tr>\n" +
                "            <th th:each=\"header : ${headers}\">\n" +
                "                <span th:text=\"${header}\">Header</span>\n" +
                "            </th>\n" +
                "        </tr>\n" +
                "        </thead>\n" +
                "        <tbody>\n" +
                "        <tr th:each=\"row : ${rows}\">\n" +
                "            <td th:each=\"cell : ${row}\">\n" +
                "                <span th:text=\"${cell}\">Cell</span>\n" +
                "            </td>\n" +
                "        </tr>\n" +
                "        </tbody>\n" +
                "    </table>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";
        ConvertHtmlToPdf(context, "C:\\Users\\XingL\\Desktop\\bb3.pdf");
    }

    /**
     * 拼接pdf
     *
     * @param inputPath1
     * @param inputPath2
     * @param outputPath
     */
    public static void mergePdf(String inputPath1, String inputPath2, String outputPath) {
        try {
            Document pdfDocument1 = new Document(inputPath1);
            Document pdfDocument2 = new Document(inputPath2);

            pdfDocument1.getPages().add(pdfDocument2.getPages());
            pdfDocument1.save(outputPath, SaveFormat.Pdf);
            System.out.println("PDF合并成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将多个PDF文件合并成一个PDF文件
     *
     * @param pdfFiles
     * @param outputPath
     */
    public static void mergePdfFiles(String[] pdfFiles, String outputPath) {
        try {
            PdfFileEditor pdfFileEditor = new PdfFileEditor();
            pdfFileEditor.concatenate(pdfFiles, outputPath);
            System.out.println("PDF合并成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 替换现有 PDF 文件中的文本
     */
    public static void ReplaceText01() {

        PdfContentEditor editor = new PdfContentEditor();
        // 绑定 PDF 文件
        editor.bindPdf("sample.pdf");
        // 替换文本
        editor.replaceText("Value", "Label");
        // 设置字体大小
        editor.replaceText("Value", "Label", 12);
        // 设置字体颜色(使文本加粗、斜体、彩色)
        TextState textState = new TextState(Color.getRed().toRgb(), 12);
        editor.replaceText("Value", "Label", textState);

        // 替换所有文本
        int count = 0;
        while (editor.replaceText("Value", "Label")) count++;
        // 特定页面上进行所有文本替换
        while (editor.replaceText("9999", 2, "ABCDE")) count++;
        // 保存文件
        editor.save("PdfContentEditorDemo01.pdf");
    }


    /**
     * 替换文本
     *
     * @param inputPath
     * @param outputPath
     * @param searchText
     * @param replaceText
     */
    public static void replaceText(String inputPath, String outputPath, String searchText, String replaceText) {
        try {
            Document document = new Document(inputPath);

            // 创建 TextFragmentAbsorber 对象
            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(replaceText);
            // 遍历所有文本片段
            document.getPages().accept(textFragmentAbsorber);
            // 获取文本片段集合
            TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments();
            // 设置文本片段
            TextFragment setText = textFragmentCollection.get_Item(1);
            // 设置替换文本
            setText.setText(searchText);
            document.save(outputPath, SaveFormat.Pdf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增pdf页面
     *
     * @param inputFile
     * @param insertLocation
     * @param portFile
     * @param startPage
     * @param endPage
     * @param outputFile
     */
    public static void addPage(String inputFile, int insertLocation, String portFile, int startPage, int endPage, String outputFile) {
        PdfFileEditor pdfFileEditor = new PdfFileEditor();
        pdfFileEditor.insert(inputFile, insertLocation, portFile, startPage, endPage, outputFile);
    }

    /**
     * 删除 PDF 页面
     *
     * @param inputPath
     * @param outputPath
     * @param pageNumberToDelete
     */
    public static void deletePage(String inputPath, String outputPath, int[] pageNumberToDelete) {
        PdfFileEditor pdfFileEditor = new PdfFileEditor();
        pdfFileEditor.delete(inputPath, pageNumberToDelete, outputPath);
    }


    /**
     * 拆分pdf
     *
     * @param inputPath
     * @param outputFolder
     */
    public static void splitPdfFile(String inputPath, String outputFolder) {
        try (Document pdfDocument = new Document(inputPath)) {
            // 获取 PDF 文件的总页数
            int totalPages = pdfDocument.getPages().size();
            PdfFileEditor pdfEditor = new PdfFileEditor();

            for (int i = 1; i <= totalPages; i++) {
                // 动态生成每一页的 PDF 文件名
                String outputFileName = outputFolder + "page_" + i + ".pdf";
                // 生成每一页的 PDF
                pdfEditor.extract(inputPath, i, i, outputFileName);
            }
        } catch (Exception e) {
            System.err.println("未知错误: " + e.getMessage());
        }
    }

    /**
     * pdf转换为jpg
     *
     * @param inputPath
     * @param outputFolder
     */
    public static void convertPdfToJpg(String inputPath, String outputFolder) {
        // 使用 try-with-resources 确保 PdfConverter 能够被正确关闭
        try (PdfConverter converter = new PdfConverter()) {
            // 绑定输入 PDF 文件
            converter.bindPdf(inputPath);
            // 初始化转换过程
            converter.doConvert();
            int count = 0;
            // 检查是否存在页面，并逐个转换为图像
            while (converter.hasNextImage()) {
                // 添加时间戳以避免文件名冲突
                String fileName = outputFolder + "page" + count + "_" + System.currentTimeMillis() + "_out.jpg";
                converter.getNextImage(fileName, ImageType.getJpeg());
                count++;
            }
        } catch (Exception e) { // 捕获并处理异常
            e.printStackTrace();
        }
    }

    /**
     * 创建pdf
     *
     * @param outputFileName
     */
    public static void createPdf(String outputFileName) {
        try (Document document = new Document()) {
            Page page = document.getPages().add();
            page.getParagraphs().add(new TextFragment("Hello World!"));
            document.save(outputFileName);
        } catch (Exception e) {
            System.err.println("Error creating PDF: " + e.getMessage());
        }
    }

    /**
     * pdf进行签名
     *
     * @param inputFilePath
     * @param outputFilePath
     * @param certificatePath
     * @param password
     */
    public static void SignDocument(String inputFilePath, String outputFilePath, String certificatePath, String password) {
        try {
            Document document = new Document(inputFilePath);
            // 创建签名对象
            PdfFileSignature signature = new PdfFileSignature(document);
            // 加载证书
            PKCS7 pkcs = new PKCS7(certificatePath, password); // Use PKCS7/PKCS7Detached
            // 签名
            signature.sign(1, true, new java.awt.Rectangle(300, 100, 400, 200), pkcs);
            // 保存签名后的文件
            signature.save(outputFilePath);
        } catch (Exception e) {
            System.err.println("其他异常: " + e.getMessage());
        }
    }


    /**
     * 将HTML转换为Pdf
     *
     * @param inputPath
     * @param outputPath
     */
    public static void convertHTMLToPDF(String inputPath, String outputPath) {
        try {
            Document pdfDocument = new Document(inputPath);
            pdfDocument.save(outputPath, SaveFormat.Pdf);
            System.out.println("HTML转换为PDF成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将Pdf转换为html
     *
     * @param inputPath
     * @param outputPath
     */
    public static void convertPDFToHTML(String inputPath, String outputPath) {
        try {
            Document pdfDocument = new Document(inputPath);
            pdfDocument.save(outputPath, SaveFormat.Html);
            System.out.println("PDF转换为HTML成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将PDF转换为Word
     *
     * @param inputPath  输入Word文件的路径
     * @param outputPath 输出PDF文件的路径
     * @param fontDir    字体目录的路径
     */
    public static void convertPDFToWord(String inputPath, String outputPath, String fontDir) {
        try {
            Document pdfDocument = new Document(inputPath);

            // 创建字体设置
            FontSettings fontSettings = new FontSettings();
            // 设置字体目录
            fontSettings.setFontsSources(new FontSourceBase[]{new SystemFontSource(), new FolderFontSource(fontDir, true)});
            // 设置字体设置
            pdfDocument.setFitWindow(true);

            pdfDocument.save(outputPath, SaveFormat.Doc);
            System.out.println("PDF转换为Word成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void mainXml() {
        String TEMP_HTML_FILE_NAME = "temp.html";
        String PDF_OUTPUT_FILE_NAME = "HelloWorld_out.pdf";
        try {
            // 创建 Thymeleaf 上下文并设置变量
            Context context = new Context();
            context.setVariable("title", "Hello World!");
            context.setVariable("greeting", "Hello World!");

            // 创建 Thymeleaf 模板引擎
            TemplateEngine templateEngine = new TemplateEngine();

            // 渲染模板
            String renderedHtml = templateEngine.process("hello-world", context);

            // 将渲染后的 HTML 写入临时文件
            File tempHtmlFile = new File(TEMP_HTML_FILE_NAME);
            try (FileWriter fileWriter = new FileWriter(tempHtmlFile)) {
                fileWriter.write(renderedHtml);
            }

            // 使用 Aspose.Words 将 HTML 转换为 PDF
            Document doc = new Document(tempHtmlFile.getPath());
            doc.save(PDF_OUTPUT_FILE_NAME, SaveFormat.Pdf);

            // 清理临时文件
            tempHtmlFile.delete();
        } catch (Exception e) {
            System.err.println("Error generating PDF: " + e.getMessage());
        }
    }

    public static void ConvertHtmlToPdf(String htmlContent, String outputPdfPath) {
        // 创建 PDF 文档实例
        Document pdfDocument = new Document();

        // 使用转换后的 HTML 字符串创建 HtmlFragment
        Page page = pdfDocument.getPages().add();
        page.getParagraphs().add(new HtmlFragment(htmlContent));

        // 保存 PDF 文档到指定路径
        pdfDocument.save(outputPdfPath, SaveFormat.Pdf);
    }
}
